package com.yuexunit.mobilenurse.module.DocAdvice.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.adapter.OutMedicineListAdapter;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Medicine;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderExec;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXExecuteOrder;
import com.yuexunit.mobilenurse.module.DocAdvice.model.impl.OutMedicineModel;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.IOutMedicinePresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.impl.OutMedicinePresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.view.IOutMedicine;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.Dialog_Pass;
import com.yuexunit.mobilenurse.widget.Dialog_Success;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/2 0002.
 */

public class Frag_OutMedicine extends KJFragment implements IOutMedicine {
    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;
    @Bind(R.id.injection_list)
    public FixedSwipeListView injection_list;
    @Bind(R.id.check_outmedicine)
    CheckBox checkOutmedicine;

    private BaseAdapter adapter;
    Act_DocAdvice aty;
    //病人住院号
    private String visitno;
    //记录Log
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    LoadingDialog loadingDialog;

    IOutMedicinePresenter presenter;

    //来源
    boolean source;
    //位置
    private int position;
    //医嘱标识条码
    private String barcode;

    //定时器时间
    int countTime = 3;

    Dialog_Fail.Builder builder_fail;
    Dialog_Success.Builder builder_success;

    Handler handler_noid;
    Timer time;
    TimerTask timetask;

    ArrayList<DocAdvice_Medicine> docAdvice_all = new ArrayList<DocAdvice_Medicine>();
    ArrayList<DocAdvice_Medicine> docAdvice_exec = new ArrayList<DocAdvice_Medicine>();

    private int exec_success = 0;
    //    private boolean isFinish = false;
    private int exec_now = -1;

    @Override
    protected View inflaterView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        aty = (Act_DocAdvice) getActivity();
        View layout = View.inflate(aty, R.layout.frag_outmedicine, null);
        ButterKnife.bind(this, layout);
        return layout;
    }


    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        if (presenter == null) {
            presenter = new OutMedicinePresenter(this, new OutMedicineModel());
        }
        visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });
        if (SystemTool.checkNet(aty)) {
            presenter.showMedicineList(visitno);
        } else {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void showMedicineList(ArrayList<DocAdvice_Medicine> list) {
        docAdvice_all = list;
        adapter = new OutMedicineListAdapter(Frag_OutMedicine.this, aty, docAdvice_all);
        injection_list.setAdapter(adapter);
        mEmptyLayout.dismiss();
    }

    @Override
    public void execDialog(int status, String message) {
        switch (status) {
            case 1:
                if (exec_now == (docAdvice_exec.size() - 1)) {
                    execResult();
                } else {
                    exec_now++;
                    presenter.Execorder_outmedicine(AppConfig.VISITNO, docAdvice_exec.get(exec_now).getDocAdvice_orderlist().getOrdergroupno() + "", AppConfig.NURSEID);
                }
                break;
            case 2:
                exec_success++;
                if (exec_now == (docAdvice_exec.size() - 1)) {
                    execResult();
                } else {
                    exec_now++;
                    presenter.Execorder_outmedicine(AppConfig.VISITNO, docAdvice_exec.get(exec_now).getDocAdvice_orderlist().getOrdergroupno() + "", AppConfig.NURSEID);
                }
                break;

        }
    }

    @Override
    public void getExecData(YXExecuteOrder executeOrderData) {
        ArrayList<DocAdvice_OrderExec> docAdvice_orderExecs = docAdvice_all.get(position).getDespensing_exec();
        for (int i = 0; i < docAdvice_orderExecs.size(); i++) {
            if (barcode.equals(docAdvice_orderExecs.get(i).getBarcode())) {
                docAdvice_orderExecs.get(i).setExecdate(executeOrderData.getResponse().getOrderexecinfo().getExecdate() + "");
                docAdvice_orderExecs.get(i).setExecempid(executeOrderData.getResponse().getOrderexecinfo().getExecempid());
                docAdvice_orderExecs.get(i).setExecseq(executeOrderData.getResponse().getOrderexecinfo().getExecseq());
                docAdvice_orderExecs.get(i).setExectime(executeOrderData.getResponse().getOrderexecinfo().getExectime() + "");
            }
        }
        docAdvice_all.get(position).setDespensing_exec(docAdvice_orderExecs);

        int count = 0;
        for (int i = 0; i < docAdvice_orderExecs.size(); i++) {
            if (docAdvice_orderExecs.get(i).getExecempid() == null) {
                count++;
            }
        }
        if (count > 0) {
            docAdvice_all.get(position).setCount(docAdvice_orderExecs.size() - count + "/" + docAdvice_orderExecs.size());
            docAdvice_all.get(position).setStatus("等待治疗");
        } else {
            docAdvice_all.get(position).setCount(docAdvice_orderExecs.size() - count + "/" + docAdvice_orderExecs.size());
            docAdvice_all.get(position).setStatus("已治疗");
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void execOutMedicine(YXExecuteOrder executeOrderData) {

    }

//    public void ExecuteOrder(final Boolean source,final String barcode,int position)
//    {
//        if(presenter == null)
//        {
//            presenter = new OutMedicinePresenter(this,new OutMedicineModel());
//        }
//        this.source = source;
//        this.barcode = barcode;
//        this.position = position;
//        presenter.Execorder(source, AppConfig.VISITNO, barcode, AppConfig.NURSEID);
//    }
//
//    public void ExecuteOrder_inner(final Boolean source,final String barcode,int position)
//    {
//        this.source = source;
//        this.barcode = barcode;
//        this.position = position;
//        showExecDialog();
//    }

    public void select_order(int position, boolean isCheck) {
        docAdvice_all.get(position).setCheck(isCheck);
        adapter.notifyDataSetChanged();
    }

    public void show_unpass(String message) {
        builder_fail = new Dialog_Fail.Builder(getActivity());
        builder_fail.setMessage(message);
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_fail.create().show();
    }

    public void showExecDialog() {
        builder_success = new Dialog_Success.Builder(getActivity());
        builder_success.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadingDialog = new LoadingDialog(aty);
                        loadingDialog.setCanceledOnTouchOutside(false);
                        loadingDialog.show();
                        presenter.Execorder(source, AppConfig.VISITNO, barcode, AppConfig.NURSEID);
                    }
                });

        builder_success.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_success.create().show();
    }

    public void show_pass() {
        final Dialog_Pass.Builder dialog_pass = new Dialog_Pass.Builder(aty);
        dialog_pass.create().show();
        handler_noid = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_noid.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }


    @OnClick({R.id.check_outmedicine, R.id.outmedicine_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_outmedicine:
                if (checkOutmedicine.isChecked()) {
                    for (int i = 0; i < docAdvice_all.size(); i++) {
                        docAdvice_all.get(i).setCheck(true);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < docAdvice_all.size(); i++) {
                        docAdvice_all.get(i).setCheck(false);
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
            case R.id.outmedicine_btn:
//                presenter.showMedicineList(visitno);
                docAdvice_exec = new ArrayList<>();
                exec_success=0;
                exec_now=-1;

                loadingDialog = new LoadingDialog(aty);
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();

                for (int i = 0; i < docAdvice_all.size(); i++) {
                    if (docAdvice_all.get(i).isCheck && docAdvice_all.get(i).getStatus().equals("等待发药")) {
                        docAdvice_exec.add(docAdvice_all.get(i));
                    }
                }

                if (docAdvice_exec.size() > 0) {
                    exec_now = 0;
                    presenter.Execorder_outmedicine(AppConfig.VISITNO, docAdvice_exec.get(exec_now).getDocAdvice_orderlist().getOrdergroupno() + "", AppConfig.NURSEID);
                }
                else {
                    ViewInject.toast("没有需要执行的药品");
                    loadingDialog.dismiss();
                }
                break;
        }
    }

    private void execResult() {
        presenter.showMedicineList(visitno);
        loadingDialog.dismiss();
        if (docAdvice_exec.size() == exec_success) {
            ViewInject.toast("全部执行成功");
        } else {
            if (exec_success == 0) {
                ViewInject.toast("全部执行不成功，请查看");
            } else {
                ViewInject.toast("部分执行成功，请查看");
            }
        }
    }
}
